#!/usr/bin/env python
#encoding:utf-8
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

#from checkPoSku import createConn,createTb,insertPoSku,queryPoSku
from checkPoSku import checkPonameSku
from writeLog import logInfo
from writeToErp import ReWriteToErp

import tkMessageBox
import time,chardet
import sys,os
import logging
import ConfigParser

import getpass
import platform
import json

reload(sys)
sys.setdefaultencoding('utf8')



global csvfilename
if len(sys.argv) > 1:
	csvfilename = sys.argv[1]
else:
	csvfilename = "purchase.order.csv"
print csvfilename
#print os.path.exists(filename)
	
#============= 找Firefox的配置profile.default==================
system_ , sysUser = platform.system(),getpass.getuser()
if system_ == "Windows":
	profilePath = "C:/Documents and Settings/"
	profilePath += sysUser
	profilePath += "/Application Data/Mozilla/Firefox/Profiles/"
else:
	profilePath = "/home/"
	profilePath += sysUser
	profilePath += "/.mozilla/firefox/"
profileName = ""

def endWith(s,*endstring):
	array = map(s.endswith,endstring)
	if True in array:
		return True
	else:
		return False

files = os.listdir(profilePath)
for filename in files:
	if endWith(filename,'.default'):
		profileName = filename

if not profileName:
	print "not found profile..."

profileName = os.path.join(profilePath,profileName)
print profileName
#==================== 其他的内容 ============================
	
transctOrderFile = "tradingOrderNumber.csv"

if not os.path.exists("config"):
	os.mkdir("config")
infoFile="config/info.ini"



productFare_id = 2475     #产品运费的id

global POname_i, url_i  , content_i, count_n_i
global size_i  , color_i, date_i   , prePrice_i
global order_id_i,  unit_id_i

POname_i , url_i   ,content_i ,count_n_i   = -1, -1, -1, -1
size_i   , color_i ,date_i    ,prePrice_i  = -1, -1, -1, -1
order_id_i ,unit_id_i  =  -1, -1


################################################################
#     主要的采购流程都在这里
################################################################
logInfo("Start  info ...\n")

def encodeUTF8(strs):
	if not strs: return ""
	strsCoding = chardet.detect(strs).get("encoding")
	#print strs
	if not strsCoding: return strs
	if strsCoding == "utf8" or strsCoding == "utf-8": return strs
	if strsCoding == "ascii":
		try:
			strs = strs.encode("utf-8")
		except Exception,e:
			logInfo("ascii encode Error,%s"%e)
	if strsCoding != "utf-8" and strsCoding  != "utf8" and strsCoding != "ascii":
		try:
			strs = strs.decode(strsCoding).encode("utf-8")
		except Exception,e:
			logInfo("encode %s Error,%s"%(strs,e))
	return strs


class MyConfig():
	def __init__(self,confHead):
		self.path = infoFile
		self.confHead = encodeUTF8(confHead)
		self.cf = ConfigParser.ConfigParser()
		self.cf.read(self.path)
	def get(self, name, default=None):
		try:
			return self.cf.get(self.confHead, name)
		except:
			return default



def getInfo():
	ReveiverInfoDict = {}	
	if os.path.exists(infoFile):
		#url1688 = MyConfig("url").get("url1688","")
		#username = MyConfig("userPass").get("username","")
		#password = MyConfig("userPass").get("password","")
 		#logfilename = MyConfig("logfilename").get("logfilename","1688.log")
	
		config = MyConfig("receiveInfo")
		#收货地址信息
		"""
		ReveiverInfoDict = {
			"inputUser":encodeUTF8(config.get("inputUser")),               #收货人姓名
			"province" :encodeUTF8(config.get("province")),                 #省市
			"city"     :encodeUTF8(config.get("city")),                     #城市
			"area"     :encodeUTF8(config.get("area")),                     #城市区域
			"inputAddr":encodeUTF8(config.get("inputAddr")),               #街道地址
			"inputPost":encodeUTF8(config.get("inputPost")),                #邮编   
			"inputMobile":encodeUTF8(config.get("inputMobile")),            #手机
			"phoneCode":encodeUTF8(config.get("phoneCode")),                #区号,如0777
			"phoneNum" :encodeUTF8(config.get("phoneNum")),                 #号码,如87582688
			"phoneSub" :encodeUTF8(config.get("phoneSub"))}                 #分机号,如12
		"""
		ReveiverInfoDict = {
		"inputUser":config.get("inputUser"),               #收货人姓名
		"province" :config.get("province"),                 #省市
		"city"     :config.get("city"),                     #城市
		"area"     :config.get("area"),                     #城市区域
		"inputAddr":config.get("inputAddr") ,               #街道地址
		"inputPost":config.get("inputPost"),                #邮编   
		"inputMobile":config.get("inputMobile"),            #手机
		"phoneCode":config.get("phoneCode"),                #区号,如0777
		"phoneNum" :config.get("phoneNum"),                 #号码,如87582688
		"phoneSub" :config.get("phoneSub")}                 #分机号,如12

	else:
		tkMessageBox.showinfo("Error","config目录下没有info.ini文件")
		sys.exit()

	return ReveiverInfoDict




#################  读取csv 文件   ####################
def read_csvfile(csvfilename):
	csvfiles = ""
	try:
		csvf = open(csvfilename,"rb")
		csvfiles = csvf.readlines()
		csvf.close()
	except Exception,e:
		logInfo("Error,%s"%e)
	return csvfiles

def open_browser():
	driver = ""
	try:
		if profileName:
			profile = webdriver.FirefoxProfile(profileName)
			driver = webdriver.Firefox(profile)
		else:
			driver = webdriver.Firefox()
		#driver.maximize_window()      #将浏览器最大化
	except Exception,e:
		logInfo("open browser Error,%s"%e)
	return driver

def close_browser(driver):
	try:
		driver.quit()
	except Exception,e:
		logInfo("Close browser Error,%s"%e)

############# 读取文件，并找到相应字段的位置  ####################
def figure_content(csvfiles,driver):
	preUrl,prePoName = "",""
	PoNameList,conList,urls = [],[], []
	global POname_i, url_i, content_i, count_n_i
	global size_i, color_i, date_i, prePrice_i
	global order_id_i,  unit_id_i
	
	nameLines = csvfiles[0]
	nameLines = nameLines.split(",")
	for i in range(len(nameLines)):
		#print len(nameLines[i])
		nameLines[i] = nameLines[i].replace("\"","")
		if encodeUTF8("单号") == encodeUTF8(nameLines[i]).replace("\"","") \
				or "name" == nameLines[i].lower() or len(encodeUTF8(nameLines[i])) == 6: 
	   		POname_i = i
		elif "url" in nameLines[i].lower():
			url_i = i
		elif encodeUTF8("订单明细/产品/名称") in encodeUTF8(nameLines[i]) \
				or "name_template" in nameLines[i].lower():
			content_i = i
		elif encodeUTF8("订单明细/数量") in encodeUTF8(nameLines[i]) \
				or "product_qty" in nameLines[i].lower():
			count_n_i = i
		elif encodeUTF8("尺寸") in encodeUTF8(nameLines[i]) \
				or "size" in nameLines[i].lower():
			size_i = i
		elif encodeUTF8("颜色") in encodeUTF8(nameLines[i]) \
				or "color" in nameLines[i].lower():
			color_i = i
		elif encodeUTF8("订单明细/产品/内部单号") in encodeUTF8(nameLines[i]) \
				or "sku" in nameLines[i].lower():
			sku_i = i
		elif encodeUTF8("订单明细/计划日期") in encodeUTF8(nameLines[i]) \
				or "date" in nameLines[i].lower():
			date_i = i
		elif encodeUTF8("订单明细/last price unite") in encodeUTF8(nameLines[i]):
			prePrice_i = i
		elif encodeUTF8("External ID") in encodeUTF8(nameLines[i]):
			order_id_i = i
		elif encodeUTF8("订单明细/ID") in encodeUTF8(nameLines[i]):
			unit_id_i = i

	if -1 in [POname_i, url_i, content_i, count_n_i,order_id_i,unit_id_i]:
		logInfo("\n\t\n Error: POname_i: %s,url_i: %s,content_i: %s, count_n_i: %s, size_i: %s,color_i:%s"\
					%(POname_i,url_i,content_i, count_n_i,size_i,color_i))
		logInfo("\n\t\n Error: order_id_i: %s, unit_id_i: %s"%(order_id_i,unit_id_i))
		close_browser(driver)
		#tkMessageBox.showinfo("Error","请确保查找的文件包含 单号, url,尺寸,颜色,订单详细/产品/名称,订单明细/数量 这几个字段")
		#myexit(driver)
		
	#-------------------------    写到文件       -------------------------		
	write_transcFile("","","","",nameLines,"",wHead = "writeHead")       #写头部

	
	lineLen = len(csvfiles[0].split(","))
	for line in csvfiles[1:]:                   #第二行开始
		line = line.replace("\"","")
		line = line.lower().split(",")
		if len(line) < lineLen: continue
		POname, url, content, count_n = line[POname_i], line[url_i], line[content_i], line[count_n_i]
		size ,color,skuname = line[size_i], line[color_i],line[sku_i]
		urlname = ""
		if POname != "":
			nowPoName = prePoName = POname
			conList = []
		else:
			nowPoName = prePoName
		if "http://" in url:
			urlname = url
		#	urlname = preUrl = url
		#else:
		#	urlname = preUrl
		#urls.append(urlname)
		conList.append({"content":content,       #内容
						"count_n":count_n,       #个数
						"size"   :size,          #大小
						"color"  :color,         #颜色
						"url"    :urlname,       #url
						"lines"   :line})         #整行，最后回写erp要
		if POname != "":
			PoNameList.append({"PoName":nowPoName,"sku":skuname,"conList":conList})
	#print PoNameList
	return PoNameList


class checkPoSkuIsExists():
	def __init__(self,poNameOrSku,skuname):
		self.poNameOrSku = poNameOrSku
		self.skuname = skuname
		self.checkPoSku = self.getcheck()
	def getcheck(self):
		checkPoSku = checkPonameSku()
		checkPoSku.createTb()
		return checkPoSku
	def checkPo(self):
		checkPoSku,poNameOrSku = self.checkPoSku,self.poNameOrSku
		poQueryResult = checkPoSku.queryPoSku("poname",poNameOrSku)
		if poQueryResult:
			return True
		else:
			return False
	def checkSku(self):
		checkPoSku,poNameOrSku = self.checkPoSku,self.poNameOrSku
		skuname = self.skuname
		skuQeuryResult = checkPoSku.queryPoSku("sku",poNameOrSku)
		if skuQeuryResult:
			return True
		else:
			return False
	def insertPoAndSku(self):
		checkPoSku,poNameOrSku = self.checkPoSku,self.poNameOrSku
		skuname = self.skuname
		timeNow = time.strftime("%Y-%d-%m %H:%M:%S",time.localtime())
		checkPoSku.insertPoSku("poname",(timeNow,poNameOrSku))
		checkPoSku.insertPoSku("sku",(poNameOrSku,skuname))
		
		
################################ 自动填单部分 ########################################

class autoInputCount():
	def __init__(self,csvfiles,driver):
		self.csvfiles = csvfiles
		self.PoNameList = figure_content(self.csvfiles,driver)
		self.driver = driver
		self.ReveiverInfoDict = getInfo()
		
	def loopInput(self):
		AllPoName = []
		for line in self.PoNameList:
			if line.get("PoName") not in AllPoName:
				AllPoName.append(line.get("PoName"))          #PoName已经处理过的就跳过
			else: continue
			checkPoSku = checkPoSkuIsExists(line.get("PoName"),line.get("sku"))
			isExistsPo = checkPoSku.checkPo()
			if isExistsPo:
				isExistsSku = checkPoSku.checkSku()
				if isExistsSku:continue  #如果sqlite3数据里面已经存在，则跳过
				
			foundGoodsOrNo ,unit_price = 0, -1                          #是否找到对应的，以及单价
			
			for conList in line.get("conList"):
				if not conList.get("url"): break
				try:
					urlname = encodeUTF8(conList.get("url"))
					urlname = urlname.replace("\"","")
					#self.driver.get(conList.get("url"))                      #跳转到货物的地址上
					self.driver.get(urlname)
				except Exception,e:
					logInfo("get url: %s Error,%s"%(conList.get("url"),e))
				foundGoodsOrNo = self.findGoods(conList)                 #找到商品
				unit_price = self.getUnitPrice(conList.get("count_n"))   #获取单价
				goodsName_selector = "div#mod-detail-title.mod-detail-title > h1.d-title"
				try:
					titleOfGoods = self.driver.find_element_by_css_selector(goodsName_selector).text
				except Exception,e:
					logInfo("get title of goods Error,%s"%e)
				if int(foundGoodsOrNo) == 1:
					print foundGoodsOrNo
					try:
						self.driver.find_element_by_link_text(u"加入进货单").click()
						self.driver.implicitly_wait(2)
					except Exception,e:
						logInfo("click u'加入进货单' Error,%s"%e)
			if foundGoodsOrNo:
				purchase_Selector = "div.nav-title > a.nav-arrow > span"     #点击进货单
				self.clickByCss(purchase_Selector)                           #到进货单里面付款

				windows = self.driver.window_handles
				try:
					self.driver.switch_to_window(windows[-1])
				except Exception,e:
					logInfo("switch to windows[-1] Error,%s"%e)
				if "login.1688.com" in self.driver.current_url:
					print "Login ..."
			   	    #Login_1688(self.driver)     #如果页面跳转到login页面，则执行登录
				print windows
				if u"我的进货单" in self.driver.title:
					self.driver.implicitly_wait(2)
					self.goPurChaseList( line.get("PoName"), titleOfGoods ,line, unit_price)
			   	    #self.driver.close()       #订单下完成后，可以用driver.close()关闭那个窗口
					pass
				try:
					self.driver.switch_to_window(windows[0])   #返回第一个窗口
				except Exception,e:
					logInfo("switch to windows[0] Error,%s"%e)

	#============================= 获取批发价格 ==============================
	def getUnitPrice(self,count_n):
		unit_price = -1
		if count_n: pass
		else: return unit_price
		price_dict_1 = None
		price_dict_2 = None
		price_dict_3 = None
		td_leadder1_css = "td.ladder-3-1"
		td_leadder2_css = "td.ladder-3-2"
		td_leadder3_css = "td.ladder-3-3"
		leader1 = self.findElementByCss(td_leadder1_css)
		leader2 = self.findElementByCss(td_leadder2_css)
		leader3 = self.findElementByCss(td_leadder3_css)
		if leader1: price_dict_1 = json.loads(leader1.get_attribute("data-range"))
		if leader2: price_dict_2 = json.loads(leader2.get_attribute("data-range"))
		if leader3: price_dict_3 = json.loads(leader3.get_attribute("data-range"))
		
		if price_dict_1:
			print float(price_dict_1.get("end")),float(count_n)
			if float(count_n) < float(price_dict_1.get("end")):
				unit_price = float(price_dict_1.get("price"))
		if price_dict_2:
			if float(count_n) > float(price_dict_2.get("begin")) \
					and float(count_n) < float(price_dict_2.get("end")):
				unit_price = float(price_dict_2.get("price"))
		if price_dict_3:
			if float(count_n) > float(price_dict_3.get("begin")):
				unit_price = float(price_dict_3.get("price"))
		return unit_price
		pass

	def findGoods(self,con):
		foundGoodsOrNo = 0
		#element_color = self.driver.find_element_by_css_selector("ul.list-leading")
		#self.driver.find_element_by_css_selector("span.obj-title").text       #找颜色部分
		#print element_color.text

		#如果，页面上产品只有一种，则直接选择数量即可
		#如果有多种，则先找颜色，没有找到，则找尺寸，两种都无法匹配到，则放弃
		#找颜色，
		#driver.find_element_by_css_selector("div.tb-skin").text   #find整个框
		#driver.find_element_by_css_selector("div.obj-sku").text
				
		table_sku_css = "table.table-sku > tbody"
		d_content_xpath = "../../../.."   #从tbody 到 div[@class='d-content']  ,xpath ='../../../..'
		table_sku = self.findElementByCss(table_sku_css)
		d_content = self.findElementByXpath(d_content_xpath,table_sku)

		con_have_size, con_have_color = "",""
		try:
			con_have_color = con.get("color")
		except Exception,e:
			logInfo("con not found color ...")
		if con_have_color:
			foundGoodsOrNo = self.findGoodsClickColor(con,d_content)
				
		try:
			con_have_size = con.get("size")
		except Exception,e:
			logInfo("con not found size ...")
		if con_have_size:
			foundGoodsOrNo = self.findGoodsClickSize(con,d_content)
			
		table_sku_css_tr = "tbody > tr[data-sku-config]"
		table_sku_n = self.fElementsByCss(table_sku_css_tr)
		if not foundGoodsOrNo:
			print len(table_sku_n)
			if  0 < len(table_sku_n) and len(table_sku_n) <= 1:
				foundGoodsOrNo = self.inputCounts(con, table_sku_n[0], useCss = True)
			else:
				foundGoodsOrNo = self.sku_find(con,d_content)

		if not foundGoodsOrNo:                                   #如果页面元素与众不同
			amount_input_css = "div.unit-detail-amount-control"  #没有tbody > tr[data-sku-config]的页面
			amount_input_ = self.findElementByCss(amount_input_css)
			foundGoodsOrNo = self.inputCounts(con, amount_input_, useCss = True)
			pass
		return foundGoodsOrNo


	def findGoodsClickColor(self,con,d_content):
		foundGoodsOrNo = 0
		colors_div_css = "div.unit-detail-spec-operator"
		all_colors = self.fElementsByCss(colors_div_css)
		for color in all_colors:
			colorname_web = color.get_attribute("data-unit-config")
			colorname_web = json.loads(colorname_web)
			color_web_name = colorname_web.get("name")
			colorname_file = encodeUTF8(con.get("color"))
			#print colorname_file,color_web_name
			if color_web_name in colorname_file or colorname_file in color_web_name:
				color.click()
				foundGoodsOrNo = self.sku_find(con,d_content, findtype="color")
		return foundGoodsOrNo


	def findGoodsClickSize(self,con,d_content):
		foundGoodsOrNo = 0
		size_div_css = "div.unit-detail-spec-operator"
		all_sizes = self.fElementsByCss(size_div_css)
		for size in all_sizes:
			size_web = size.get_attribute("data-unit-config")
			size_web = json.loads(size_web)
			size_web_name = size_web.get("name")
			size_file = encodeUTF8(con.get("size"))
			if size_web_name == size_file:
				size.click()
				foundGoodsOrNo = self.sku_find(con, d_content, findtype = "size")
		return foundGoodsOrNo

	def sku_find(self,con,d_content, findtype=None):
		foundGoodsOrNo = 0
		data_sku_config_css = "tbody > tr[data-sku-config]"
		all_sku = self.fElementsByCss(data_sku_config_css)
		for skus in all_sku:
			skuConfig = json.loads(skus.get_attribute("data-sku-config"))
			skuName = skuConfig.get("skuName")
			if findtype == "size":                              #上面已经选择了颜色
				if skuName == con.get("color"):
					foundGoodsOrNo = self.inputCounts(con, skus, useCss = True)
			if findtype == "color":                            #如果头已经是颜色，则现在选择size
				if skuName == con.get("size"):
					foundGoodsOrNo = self.inputCounts(con, skus, useCss = True)
			if not foundGoodsOrNo:
				if skuName == con.get("color") or skuName == con.get("size"):
					foundGoodsOrNo = self.inputCounts(con, skus, useCss = True)
				pass
		return foundGoodsOrNo

	
	#------------------------------  输入count ------------------------------
	def inputCounts(self,con, data_sku, useCss = False):     #根据
		inputN = 0
		if useCss:
			amount_input_css = "input.amount-input"
			element_input = self.findElementByCss(amount_input_css, data_sku)
		else:
			amount_input_xpath = "td[@class='amount']/div/div/input[@class='amount-input']"
			element_input = self.findElementByXpath(amount_input_xpath, data_sku)
		if "str" not in str(type(element_input)):
			try:
				element_input.clear()
				element_input.send_keys('%s'%con.get("count_n"))
				inputN = 1
			except Exception,e:
				logInfo("input Counts Error,%s"%e)
		time.sleep(1)
		return inputN


	def goPurChaseList(self, PoName, titleOfGoods, line, unit_price):
		titleOfGoods = titleOfGoods.split(" ")  #将名称按两个空格划分
		print u"%s"%titleOfGoods
		titlenameCss = "div.main > div.description.text-medium > a"
		checkboxCssPath = "div.opt > span.lang-checkbox > label"
		allTitleName = []
		try:
			allTitleName = self.driver.find_elements_by_css_selector("div.zone-goods.fd-clr")
		except Exception,e:
			logInfo("find zone-goods.fd-clr Error,%s"%e)
		try:
			for titleName in allTitleName:
				for names in titleOfGoods: #货品名称
					titleNameText = self.findElementByCss(titlenameCss)
				    #print names,titleName.find_element_by_css_selector(titlenameCss).text
				    #print names in titleName.find_element_by_css_selector(titlenameCss).text
   				    #if names in titleName.find_element_by_css_selector(titlenameCss).text:
					if not titleNameText: continue
					logInfo( names + " : " + titleNameText.text)
					logInfo( names in titleNameText.text)
					if names in titleNameText.text:
						try:
							select_input_css = "input.select-input"
							alipay_xpath = "../../div[2]/dl[2]/dt"
							select_container = self.findElementByCss(select_input_css,titleName)
							select_container.click()
							alipay = self.findElementByXpath(alipay_xpath,select_container)
							alipay.click()
						except Exception,e:
							logInfo("select_continer Error,%s"%e)
						self.clickByCss(checkboxCssPath, titleName)
						print self.findElementByCss(checkboxCssPath,titleName).get_attribute("for")
						time.sleep(1)
						self.clickByCss("button.checkout")
						time.sleep(1)
						try:
							if self.driver.find_element_by_css_selector("a.edit-address-info"):
								self.edit_ReceiveInfo(PoName)
						except Exception,e:
							logInfo("a.edit-address-info Error,%s"%e)
							self.input_ReceiveInfo(PoName)
						self.input_LeavMessage(PoName)    #输入留言
						orderStatus = self.getCost_Sub_order()          #点击提交
						time.sleep(2)
						if orderStatus:
							poNameOrSku,skuname = line.get("PoName"),line.get("sku")
							checkPoSku = checkPoSkuIsExists(poNameOrSku,skuname)
							checkPoSku.insertPoAndSku()						
						self.get_transactOrder_number(PoName, line, unit_price)   #获取订单信息
						time.sleep(1)
						break
					else:
						continue
				time.sleep(1)
		except Exception,e:
			logInfo("Error,%s"%e)



	#======================================= 获取交易号、订单号 =====================================
	def get_transactOrder_number(self, PoName, line, unit_price):
		windows = self.driver.window_handles
		self.driver.switch_to_window(windows[-1])
		try:
			myali = self.driver.find_element_by_partial_link_text("我的阿里")   
			ActionChains(self.driver).move_to_element(myali).perform()    #将鼠标移动到 我的阿里 这里
			self.driver.find_element_by_link_text(u"已买到货品").click()    #点击 已买到货品
			time.sleep(1)
			self.driver.switch_to_frame(0)

			orderDetail = self.findElementByCss("a.bannerOrderDetail")        #点击 订单详情
			print not orderDetail
			if not orderDetail:
				self.driver.switch_to_default_content()
				self.driver.switch_to_frame(1)
				orderDetail = self.findElementByCss("a.bannerOrderDetail")
			if orderDetail:
				orderDetail.click()
		except Exception,e:
			logInfo("Error,%s"%e)
			
		windows = self.driver.window_handles
		self.driver.switch_to_window(windows[-1])
		time.sleep(1)
		orderCss = "div.order-buyer-info > ul > li "                  #选中订单号的css		
		transctCss = "div.order-buyer-info > ul > li + li "           #选中交易号的css(同一级目录)
		shipMentCss =  "div.total.total-normal"

		orderCss_panel = "div.panel-content > ul > li"
		transctCss_panel = "div.panel-content > ul > li + li"
		#shipMent
		
		transctText = self.findElementByCss(transctCss)
		orderText = self.findElementByCss(orderCss)
		shipMent = self.findElementByCss(shipMentCss)

		if transctText: transctText = transctText.text
		else:
			transctText = self.findElementByCss(transctCss_panel)
			if transctText: transctText = transctText.text
		if orderText: orderText = orderText.text
		else:
			orderText = self.findElementByCss(orderCss_panel)
			if orderText: orderText = orderText.text
		if shipMent: shipMent = shipMent.text                               
		else:       #如果直接用div.total.total-normal找不到运费shipMent,则用总付-总额
			total_price_number,total_pay = "",""
			total_price = self.findElementByCss("tr.item.first-item")
			if total_price:
				totalPriceXpath = "td[@rowspan='1']/div"
				total_price_number = self.findElementByXpath(totalPriceXpath,total_price)
			if total_price_number:
				total_pay_css = "em.stress.total-price"
				total_pay = self.findElementByCss(total_pay_css)
				if total_pay: total_pay = total_pay.text
			if total_pay:
				shipMent = float(total_pay) - float(total_price_number)
				
		#print transctText,orderText,shipMent,line.get("conList")[0].get("lines"),line
		write_transcFile(PoName,transctText, orderText, shipMent, line.get("conList")[0].get("lines"),unit_price)
		windows = self.driver.window_handles
		if len(windows) != 1:
			self.driver.close()       #关闭交易号弹出的窗口
		self.driver.switch_to_window(windows[0])
		if transctText and orderText: return True
		else: return False
		
	#======================================= 输入留言信息 ===========================================
	def input_LeavMessage(self,PoName):
		PoName = u"%s"%(PoName)
		LeaveSeletor = "div.textarea-content > textarea.input"
		self.clickByCss("div.textarea-trigger")   #先点击，才能输入
		self.inputByCss(LeaveSeletor, PoName)
		pass
	
	#=======================================  修改收货信息  =========================================
	def edit_ReceiveInfo(self,PoName):
		time.sleep(1)
		self.clickByCss("a.edit-address-info")
		time.sleep(1)
		self.clickByCss("a.edit")
		self.input_ReceiveInfo(PoName)
		pass

	#========================================  输入收货信息  =========================================
	def input_ReceiveInfo(self, PoName):
		ReveiverInfoDict = self.ReveiverInfoDict
		inputAddress = ""
		inputAddress = PoName + ReveiverInfoDict.get("inputAddr") 
		#输入收货人
		cssSelector = "input.input-large.input-username"
		self.inputByCss(cssSelector, ReveiverInfoDict.get("inputUser"))
		#选择所在区域
		try:
			self.driver.find_element_by_css_selector("select.input-select.select-province").click()       #点击下拉
			xpathProvince = "//select[@class='input-select select-province']/option[contains(text(),'%s')]"\
				%(ReveiverInfoDict.get("province"))
			self.clickByXpath(xpathProvince)
			xpathCity = "//select[@class='input-select select-city']/option[contains(text(),'%s')]"\
				%(ReveiverInfoDict.get("city"))
			self.clickByXpath(xpathCity)
			xpathArea = "//select[@class='input-select select-area']/option[contains(text(),'%s')]"\
				%(ReveiverInfoDict.get("area"))
			self.clickByXpath(xpathArea)
		except Exception,e:
			logInfo("Select Error,%s"%e)
		#街道地址
		cssSelector = "textarea.input.input-large.input-address"
		#self.inputByCss(cssSelector, ReveiverInfoDict.get("inputAddr"))
		self.inputByCss(cssSelector, inputAddress)
		#邮编
		cssSelector = "input.input.input-large.input-post"
		self.inputByCss(cssSelector, ReveiverInfoDict.get("inputPost"))
		#手机
		cssSelector = "input.input.input-large.input-mobile"
		self.inputByCss(cssSelector , ReveiverInfoDict.get("inputMobile"))
		#分机号
		cssSelector = "input.input.input-large.input-phonecode"
		self.inputByCss(cssSelector, ReveiverInfoDict.get("phoneCode"))       #区域
		cssSelector = "input.input.input-large.input-phonenumber"
		self.inputByCss(cssSelector, ReveiverInfoDict.get("phoneNum"))        #号码
		cssSelector = "input.input.input-large.input-phonesub"
		self.inputByCss(cssSelector, ReveiverInfoDict.get("phoneSub"))        #分机号

		#确认收货信息
		saveCssSelector = "a.button.button-stress.save"
		self.driver.find_element_by_css_selector(saveCssSelector).click()
		pass

	#=========================== 获取订单费用并且提交订单  ================================
	def getCost_Sub_order(self):
		total_freight, goods_total, due_total = "","",""
		status = False
		try:
			summaryContainer = self.driver.find_element_by_css_selector("div.summary-container")
			total_freight = summaryContainer.find_element_by_css_selector("em.freight-total").text
			goods_total = summaryContainer.find_element_by_css_selector("em.goods-total").text
			due_total = summaryContainer.find_element_by_css_selector("em.due-total.text-stress").text
			self.clickByCss("input#trade-mode-checkbox")
			summaryContainer.find_element_by_link_text(u"提交订单").click()
			status = True
			time.sleep(2)
			self.driver.close()
		except Exception,e:
			logInfo("Error,%s"%e)

		summaryCost = {"totalFreight":total_freight, #总共运费
					   "goodsTotal":goods_total,     #货品总金额
					   "dueToal":due_total           #应付总额(不包括运费)
					   }
		return status


	

		#-------------------------以下为方法，非流程 ----------------------------
		
	#============================ 根据 选择css 来点击 =====================================
	def clickByCss(self, cssSelector, cssSelectorNode = ""):
		try:
			if cssSelectorNode:
				cssSelectorNode.find_element_by_css_selector(cssSelector).click()
			else:
				self.driver.find_element_by_css_selector(cssSelector).click()
		except Exception,e:
			logInfo("Click Error : %s, %s"%(cssSelector,e))


	#================================= 根据 xpath 来点击 =====================================
	def clickByXpath(self, xpathName, xpathNameNode = ""):
		try:
			if xpathNameNode:
				xpathNameNode.find_element_by_xpath(xpathName).click()
			else:
				self.driver.find_element_by_xpath(xpathName).click()
		except Exception,e:
			logInfo("By Xpath Click Error : %s ,%s"%(xpathName,e))

	#============================= 根据xpath 来输入 inputText ==============================
	def inputByXpath(self, xpathName, inputText, xpathNode = None):
		try:
			if xpathNode:
				input_Select = xpathNode.find_element_by_xpath(xpathName)
			else:
				input_Select = self.driver.find_element_by_xpath(xpathName)
			input_Select.clear()
			input_Select.send_keys(u"%s"%(inputText))
		except Exception,e:
			logInfo("inputByXpath Error: %s,%s"%(xpathName,e))
			
	#============================= 根据 选择css来输入 内容 inputText =========================
	def inputByCss(self,cssSelector,inputText, cssSelectorNode = None):
		try:
			if cssSelectorNode:
				input_Select = cssSelectorNode.find_element_by_css_selector(cssSelector)
			else:
				input_Select = self.driver.find_element_by_css_selector(cssSelector)
			input_Select.clear()
			input_Select.send_keys(u"%s"%(inputText))
		except Exception,e:
			logInfo("input Error,%s"%e)

	#============================  根据 css 来 find_element ==============================
	def findElementByCss(self,cssSelector, cssSelectorNode = None):
		selectCss = ""
		try:
			if cssSelectorNode:
				selectCss = cssSelectorNode.find_element_by_css_selector(cssSelector)
			else:
				selectCss = self.driver.find_element_by_css_selector(cssSelector)
		except Exception,e:
			logInfo("Find Error,%s"%e)
		return selectCss
	
	#================================  find_elements ===================================
	def fElementsByCss(self,cssSelector, cssSelectorNode = None):
		selectCssS = ""
		try:
			if cssSelectorNode:
				selectCssS = cssSelectorNode.find_elements_by_css_selector(cssSelector)
			else:
				selectCssS = self.driver.find_elements_by_css_selector(cssSelector)
		except Exception,e:
			logInfo("find elements Error,%s"%e)
		return selectCssS
	
	#============================== 根据 xpath 来find_elements =========================
	def findElementByXpath(self, xpathName, xpathNameNode = None):
		xpathSelect = ""
		try:
			if xpathNameNode:
				xpathSelect = xpathNameNode.find_element_by_xpath(xpathName)
			else:
				xpathSelect = self.driver.find_element_by_xpath(xpathName)
		except Exception,e:
			logInfo("find element by xpath Error,%s"%e)
		return xpathSelect
	



def write_transcFile(PoName,transctText,orderText, shipMent,line,unit_price ,wHead=None ):
	global POname_i, url_i, content_i, count_n_i
	global size_i, color_i, date_i, prePrice_i
	global order_id_i,    unit_id_i
	print line[POname_i], line[url_i], line[content_i], line[count_n_i]
	print line[size_i],   line[color_i], line[date_i],  line[prePrice_i]
	#print line
	
	linedata = ""
	if wHead:
		transctText,orderText,shipMent,unit_price = "交易号","订单号","运费","单价/unitPrice"
		subtotal,shipMent = "小计","运费"
	for stri in line:
		stri = stri.replace("\"","")
		stri = stri.replace("\n","")
		stri = stri.replace("\r\n","")
		#if stri.endswith("\n"):
		#	stri = stri.replace("\r\n","")
		linedata += stri
		linedata += ","
	if not wHead:                                                    #写头，字段
		def split_text(nametext):
			namekey,namevalue = "",""
			try:
				nameLine = nametext.split("：")
				namekey,namevalue = nameLine[0],nameLine[1]
			except Exception,e:
				logInfo("split Error,%s"%e)
			return [namekey,namevalue]
		transctText = split_text(transctText)[1]
		orderText = split_text(orderText)[1]
		shipMentValue = split_text(shipMent)[1]
		subtotal = float(line[count_n_i]) * float(unit_price)
	#------------------------------   --------------------------------	
	linedata = line[POname_i]     + "," \
	           + line[order_id_i] + "," \
			   + line[date_i]     + "," \
			   + line[count_n_i]  + "," \
			   + str(unit_price)  + "," \
			   + str(subtotal)    + "," \
			   + line[color_i]    + "," \
			   + line[size_i]     + "," \
			   + line[url_i]      + "," \
			   + line[prePrice_i] + "," \
			   + transctText      + "," \
			   + orderText        + "," \
			   + line[unit_id_i]  + "," \
			   + str(shipMent)    + "," \
			   + str(unit_price)
	linedata = linedata.replace("\r\n","")
	if wHead:
		transctFile = open(transctOrderFile,"w")                  #追加写内容
		#transctFile.write(encodeUTF8(line))
		transctFile.write(linedata+"\n")
		transctFile.close()
		return
	print transctText,orderText,shipMent
	if not os.path.exists(transctOrderFile):
		os.mknod(transctOrderFile)
	try:
		transctFile = open(transctOrderFile,"a")                  #追加写内容
		transctFile.write(linedata)
		transctFile.close()
	except Exception,e:
		logInfo("Write transctFile Error,%s"%e)
	#----------------------- write to Erp  ------------------------------
	order_id = line[order_id_i]
	unit_id  = line[unit_id_i]
	
	fieldNotes = { "notes": str(transctText) + str(orderText)}
	fieldUnit  = { "price_unit" :  unit_price }
	fieldFare  = { "name"       :  "fareNames",
				   "order_id"   :  order_id,
				   "product_id" :  productFare_id,    #运费的id
				   "product_qty":  1,
				   "date_lanned":  str(line[date_i]),
				   "product_uom":  3
				   }
	writeToErp(order_id,unit_id,fieldNotes,fieldUnit,fieldFare)
	#----------------------    end    -----------------------------------

#========================= 应该把交易号和订单号回写到erp上面的 =========================
def writeToErp(order_id,unit_id,fieldNotes,fieldUnit,fieldFare):
	noteid, unitid ,fieldid = None,None,None
	retoErp = ReWriteToErp()
	noteid =  retoErp.writeNotes(fieldNotes, order_id)
	if noteid: logInfo("notes write to Erp successful!111111111")
	else: logInfo("notes write to Erp Error!000000")
	
	unitid = retoErp.writeUnit(fieldUnit, unit_id)
	if noteid: logInfo("unitprice write to Erp successful!111111111")
	else: logInfo("unitprice write to Erp Error!000000")
	
	fieldid = retoErp.createFare(fieldFare)
	if fieldid: logInfo("field write to Erp successful!111111111")
	else: logInfo("unitprice write to Erp Error!000000")
	

def Login_1688(driver):
	url1688 = MyConfig("url").get("url1688","")
	username = encodeUTF8(MyConfig("userPass").get("username",""))
	password = encodeUTF8(MyConfig("userPass").get("password",""))
	#print username,password

	try:
		driver.get(url1688)
		driver.switch_to_frame(0)   #转到登录的iframe
	except Exception,e:
		logInfo("driver get or switch Error,%s"%e)
	try:
		userElement = driver.find_element_by_id("TPL_username_1")
		webdriver.ActionChains(driver).move_to_element(userElement).perform()
		userTxt = userElement.text
		print userElement.text
		if userTxt: pass
		else:
			userElement.click()
			userElement.clear()
			for strs in username.decode("utf8"):     #转成unicode才可以
				userElement.send_keys(strs)
				time.sleep(0.2)
		time.sleep(2)
		passElement = driver.find_element_by_id("TPL_password_1")
		webdriver.ActionChains(driver).move_to_element(passElement).perform()
		passElement.click()
		passElement.clear()
		for strs in password:
			passElement.send_keys(strs)
			time.sleep(0.2)
		time.sleep(3)
		
		loginBtnElement = driver.find_element_by_id("J_SubmitStatic")
		loginBtnElement.click()
	except Exception,e:
		logInfo("Error,%s"%e)

	try:
		driver.switch_to_default_content()   #转到页面上来
	except Exception,e:
		logInfo("Error,%s"%e)
	n ,startT = 0,time.time()
	while True:
		n += 1
		if driver.current_url.split(":")[1] != url1688.split(":")[1]:
			print url1688,driver.current_url
			break
		time.sleep(10)
		if n > 3*6: myexit(driver)
		nowTime = time.time()
		if nowTime - startT >= 3 * 60:
			if driver.current_url.split(":")[1] == url1688.split(":")[1]:
				myexit(driver)
				#close_browser(driver)
			#time.sleep(60)
			#driver = open_browser()
			#Login_1688(driver)
	try:
		#windows = driver.window_handles
		#driver.switch_to_window(windows[-1])
		cookie = driver.get_cookies()
	except Exception,e:
		logInfo("Get Cookie Error,%s"%e)

def myexit(driver):
	close_browser(driver)
	sys.exit()
		
def main():
	print "main start ..."
	global csvfilename
	filelines = read_csvfile(csvfilename)  #读取csv文件

	driver = open_browser()             #打开浏览器
	#driver = webdriver.Remote(desired_capabilities = DesiredCapabilities.CHROME)
	getInfo()
	#Login_1688(driver)                  #登录1688
	autoInputCount(filelines, driver).loopInput()
	close_browser(driver)

def test():
	#MainFrame().mainloop()
	#filelines = read_csvfile(filename)
	#contentLine = figure_content(filelines)
	#for i in contentLine:
	#	print i
	pass
	
if __name__ == "__main__":
	main()
	#test()

